﻿//var chat = $.connection.chatHub;
var userName = $('#chatBoxId').val();
var userInfo = $('#userInfo').val();
//var myClientId = $.connection.hub.id;
var connection = $.connection.chatHub;
function GetOnlineUsersList() {
    $.ajax({
        type: "post",
        url: "/Account/GetOnlineUsers",
        success: function (result) {
            var userList = result.Result;
            $('.onlineUsers').html('');
            var newChatWindow = '';
            jQuery.each(userList, function (i, userList) {
                newChatWindow += " <div >" +
                    "<a href=# id=\"" + userList.ID + "_" + userList.FirstName + "\" class=\"chat-window\">" + userList.FirstName + " " + userList.LastName + "</a>" +
                "</div>";
            });
            if (newChatWindow == '') {
                newChatWindow += " <div id=\"offLine\"> No one is online" +

                "</div>";
            }
            $('.onlineUsers').html(newChatWindow);
        }
    });
}

$(function () {





    $('.chat-window').live('click', function () {
        var temp = $(this).attr('id').split('_');
        // alert(temp[0]);
        createChatBox(temp[0], '', $(this).attr('id').split('_'), 0);
        //chat.server.CreateGroup()
    });
    $('#message').focus();
    // Create connection with name chat. chat is hub name that we declared in Hub

    connection.goOnlineMessage = function (employeeId) {
        GetOnlineUsersList();
        //        var newUser = "<div >" +
        //                    "<a href=# id=\"" + employeeId + "_" + emoloyeeName + "\" class=\"chat-window\">" + emoloyeeName + "</a>" +
        //                "</div>";
        //        $('.onlineUsers').append(newUser);

    }


    connection.addMessage = function (name, message, userNameChat, targetUserId) {

        var get_chat_id = name.split('_');
        //alert($('#' + name).length);

        if ($('#' + get_chat_id[0]).length <= 1) {
            //            $.connection.hub.start().done(function () {
            // chat.server.subscribe(get_chat_id[0]);
            //            });
            var splitTargetUser = targetUserId.split('_');
            createChatBox(splitTargetUser[0], '', splitTargetUser, 1, splitTargetUser[1]);

        }
        var userNameSplited = $('#chatBoxId').val().split('_');
        //        $('#discussion').append('<li><strong>' + name
        //                    + '</strong>:&nbsp;&nbsp;' + message + '</li>');
        $("#chatbox_" + get_chat_id[0] + " .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">' + get_chat_id[1] + ':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">' + message + '</span></div>').delay(2000);
    };
    // Declare a function on the chat hub so the server can invoke it. Add message method is responsible for adding messages to the client 
    //    connection.addMessage = function (message) {
    //        $('#messages').append('<li>' + message + '</li>');
    //    };

    // Send message
    //    $("#broadcast").click(function () {
    //        // Call the chat method on the server
    //        connection.send($('#msg').val(), $('#userId').val(), $('#group').val());
    //    });

    var timeout = null;
    var interval = 5000;

    // Event that will fire when server state changed
    $.connection.hub.stateChanged(function (change) {
        if (change.newState === $.signalR.connectionState.reconnecting) {
            timeout = setTimeout(function () {
                $('#state').css('backgroundColor', 'red')
                    .html('The server is unreachable...');
            }, interval);
        }
        else if (timeout && change.newState === $.signalR.connectionState.connected) {
            $('#state').css('backgroundColor', 'green')
                        .html('The server is online');

            clearTimeout(timeout);
            timeout = null;
        }
    });

    // Start the connection
    $.connection.hub.start().done(function () {
        // Fetch client id and display

        var myClientId = $.connection.hub.id;
        connection.goOnline(myClientId);
        $('#my-id').html(myClientId);
    });

})

   

    

   
    function checkChatBoxInputKey(event, chatboxtextarea, chatboxtitle,chatTempValue) {

        if (event.keyCode == 13 && event.shiftKey == 0) {
            message = $(chatboxtextarea).val();
            message = message.replace(/^\s+|\s+$/g, "");

            var targetUserId = $('#chatBoxId').val();


            $(chatboxtextarea).val('');
            $(chatboxtextarea).focus();
            $(chatboxtextarea).css('height', '44px');
            if (message != '') {
                message = message.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\"/g, "&quot;");
                var unsplitedvalue = chatboxtitle + "_" + chatTempValue;
                var userNameSplited = $('#chatBoxId').val().split('_');
//                connection.addMessage = function (name, message, userName) {
                $("#chatbox_" + chatboxtitle + " .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">' + userNameSplited[1] + ':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">' + message + '</span></div>');
//                };

                var encodedName = $('<div />').text(chatboxtitle).html();
                var encodedMsg = $('<div />').text(message).html();

                connection.send(unsplitedvalue, encodedMsg, chatTempValue, targetUserId);
//                $.connection.hub.start().done(function () {
//                    connection.send(unsplitedvalue, encodedMsg, chatTempValue, targetUserId);
//               });
                
            }
            chatHeartbeatTime = minChatHeartbeat;
            chatHeartbeatCount = 1;

            return false;
        }

        var adjustedHeight = chatboxtextarea.clientHeight;
        var maxHeight = 94;

        if (maxHeight > adjustedHeight) {
            adjustedHeight = Math.max(chatboxtextarea.scrollHeight, adjustedHeight);
            if (maxHeight)
                adjustedHeight = Math.min(maxHeight, adjustedHeight);
            if (adjustedHeight > chatboxtextarea.clientHeight)
                $(chatboxtextarea).css('height', adjustedHeight + 8 + 'px');
        } else {
            $(chatboxtextarea).css('overflow', 'auto');
        }

    }

    var chatBoxes =new Array();

    function createChatBox(chatboxtitle, minimizeChatBox, chatTemp, flag, tempName) {

        var userNameSplited = $('#chatBoxId').val().split('_');
        //alert(userNameSplited);
        var chatWindowName = '';
        if (flag == 0) {
            chatWindowName = chatTemp[1];
        }
        if (flag == 1) {
            chatWindowName = tempName;
        }

            if ($("#chatbox_" + chatboxtitle).length > 0) {
                if ($("#chatbox_" + chatboxtitle).css('display') == 'none') {
                    $("#chatbox_" + chatboxtitle).css('display', 'block');
                    restructureChatBoxes();
                    
                }
                $("#chatbox_" + chatboxtitle + " .chatboxtextarea").focus();
                return;
            }

            $(" <div />").attr("id", "chatbox_" + chatTemp[0])
    	.addClass("chatbox")
    	.html('<div class="chatboxhead"><div class="chatboxtitle">' + chatWindowName + '</div><div class="chatboxoptions"><a href="javascript:void(0)" onclick="javascript:toggleChatBoxGrowth(\'' + chatboxtitle + '\')">-</a> <a href="javascript:void(0)" onclick="javascript:closeChatBox(\'' + chatboxtitle + '\')">X</a></div><br clear="all"/></div><div class="chatboxcontent"></div><div class="chatboxinput"><textarea class="chatboxtextarea" onkeydown="javascript:return checkChatBoxInputKey(event,this,\'' + chatboxtitle + '\',\'' + userNameSplited[1] + '\');"></textarea></div>')
    	.appendTo($("body"));

            $("#chatbox_" + chatboxtitle).css('bottom', '0px');

            chatBoxeslength = 0;

            for (x in chatBoxes) {
                if ($("#chatbox_" + chatBoxes[x]).css('display') != 'none') {
                    chatBoxeslength++;
                }
            }

            if (chatBoxeslength == 0) {
                $("#chatbox_" + chatboxtitle).css('right', '20px');
            } else {
                width = (chatBoxeslength) * (225 + 7) + 20;
                $("#chatbox_" + chatboxtitle).css('right', width + 'px');
            }

            chatBoxes.push(chatboxtitle);

            if (minimizeChatBox == 1) {
                minimizedChatBoxes = new Array();

                if ($.cookie('chatbox_minimized')) {
                    minimizedChatBoxes = $.cookie('chatbox_minimized').split(/\|/);
                }
                minimize = 0;
                for (j = 0; j < minimizedChatBoxes.length; j++) {
                    if (minimizedChatBoxes[j] == chatboxtitle) {
                        minimize = 1;
                    }
                }

                if (minimize == 1) {
                    $('#chatbox_' + chatboxtitle + ' .chatboxcontent').css('display', 'none');
                    $('#chatbox_' + chatboxtitle + ' .chatboxinput').css('display', 'none');
                }
            }

            chatboxFocus[chatboxtitle] = false;

            $("#chatbox_" + chatboxtitle + " .chatboxtextarea").blur(function () {
                chatboxFocus[chatboxtitle] = false;
                $("#chatbox_" + chatboxtitle + " .chatboxtextarea").removeClass('chatboxtextareaselected');
            }).focus(function () {
                chatboxFocus[chatboxtitle] = true;
                newMessages[chatboxtitle] = false;
                $('#chatbox_' + chatboxtitle + ' .chatboxhead').removeClass('chatboxblink');
                $("#chatbox_" + chatboxtitle + " .chatboxtextarea").addClass('chatboxtextareaselected');
            });

            $("#chatbox_" + chatboxtitle).click(function () {
                if ($('#chatbox_' + chatboxtitle + ' .chatboxcontent').css('display') != 'none') {
                    $("#chatbox_" + chatboxtitle + " .chatboxtextarea").focus();
                }
            });

            $("#chatbox_" + chatboxtitle).show();
        }
        function restructureChatBoxes() {
            align = 0;
            for (x in chatBoxes) {

                chatboxtitle = chatBoxes[x];

                if ($("#chatbox_" + chatboxtitle).css('display') != 'none') {
                    if (align == 0) {
                        $("#chatbox_" + chatboxtitle).css('right', '20px');
                    } else {
                        width = (align) * (225 + 7) + 20;
                        $("#chatbox_" + chatboxtitle).css('right', width + 'px');
                    }
                    align++;
                }
            }
        }
        function closeChatBox(chatboxtitle) {
            $('#chatbox_' + chatboxtitle).css('display', 'none');
            restructureChatBoxes();
        }
        function toggleChatBoxGrowth(chatboxtitle) {
            if ($('#chatbox_' + chatboxtitle + ' .chatboxcontent').css('display') == 'none') {

                var minimizedChatBoxes = new Array();

                if ($.cookie('chatbox_minimized')) {
                    minimizedChatBoxes = $.cookie('chatbox_minimized').split(/\|/);
                }

                var newCookie = '';

                for (i = 0; i < minimizedChatBoxes.length; i++) {
                    if (minimizedChatBoxes[i] != chatboxtitle) {
                        newCookie += chatboxtitle + '|';
                    }
                }

                newCookie = newCookie.slice(0, -1)


                $.cookie('chatbox_minimized', newCookie);
                $('#chatbox_' + chatboxtitle + ' .chatboxcontent').css('display', 'block');
                $('#chatbox_' + chatboxtitle + ' .chatboxinput').css('display', 'block');
                $("#chatbox_" + chatboxtitle + " .chatboxcontent").scrollTop($("#chatbox_" + chatboxtitle + " .chatboxcontent")[0].scrollHeight);
            } else {

                var newCookie = chatboxtitle;

                if ($.cookie('chatbox_minimized')) {
                    newCookie += '|' + $.cookie('chatbox_minimized');
                }


                $.cookie('chatbox_minimized', newCookie);
                $('#chatbox_' + chatboxtitle + ' .chatboxcontent').css('display', 'none');
                $('#chatbox_' + chatboxtitle + ' .chatboxinput').css('display', 'none');
            }

        }